package com.ruoyi.manage.organization.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.enterprise.domain.SysUserExpand;
import com.ruoyi.manage.enterprise.service.ISysUserExpandService;
import com.ruoyi.manage.organization.domain.OcBusinessFinancingOrder;
import com.ruoyi.manage.organization.domain.vo.OcBusinessFinancingOrderVo;
import com.ruoyi.manage.organization.service.IOcBusinessFinancingOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * 企业融资订单Controller
 *
 * @author ruoyi
 * @date 2025-08-19
 */
@Api(tags = "企业融资订单控制器")
@RestController
@RequestMapping("/manage/order")
public class OcBusinessFinancingOrderController extends BaseController {
    /**
     * 配置表别名 默认空
     */
    private final static String TABLE_PREFIX = StrUtil.initTableAlias(null);
    @Autowired
    private IOcBusinessFinancingOrderService ocBusinessFinancingOrderService;

    @Autowired
    private ISysUserExpandService iSysUserExpandService;

    /**
     * 查询企业融资订单列表
     */
    @ApiOperation(value = "查询企业融资订单", notes = "企业融资订单管理")
    @PreAuthorize("@ss.hasPermi('manage:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(OcBusinessFinancingOrderVo ocBusinessFinancingOrder, QueryWrapper<OcBusinessFinancingOrder> queryWrapper) {
        setQueryCondition(ocBusinessFinancingOrder, queryWrapper);
        startPage();
        List<OcBusinessFinancingOrder> list = ocBusinessFinancingOrderService.selectFinancingOrderMatch(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询企业融资订单列表
     */
    @ApiOperation(value = "查询企业融资订单", notes = "企业融资订单管理")
    @GetMapping("/listByOrg")
    public TableDataInfo listByOrg(OcBusinessFinancingOrderVo ocBusinessFinancingOrder, QueryWrapper<OcBusinessFinancingOrder> queryWrapper) {
        if (StrUtil.isNotBlank(ocBusinessFinancingOrder.getOrderNo())) {
            queryWrapper.eq(TABLE_PREFIX + "fo.order_no", ocBusinessFinancingOrder.getOrderNo());
        }

        if (StrUtil.isNotBlank(ocBusinessFinancingOrder.getEnterpriseName())) {
            queryWrapper.like(TABLE_PREFIX + "om.enterprise_name", ocBusinessFinancingOrder.getEnterpriseName());
        }

        if (StrUtil.isNotBlank(ocBusinessFinancingOrder.getOrganizationName())) {
            queryWrapper.like(TABLE_PREFIX + "fo.organization_name", ocBusinessFinancingOrder.getOrganizationName());
        }

        if (ObjUtil.isNotNull(ocBusinessFinancingOrder.getApplyTimeRange()) && ocBusinessFinancingOrder.getApplyTimeRange().length == 2) {
            String[] applyTimeRange = ocBusinessFinancingOrder.getApplyTimeRange();
            queryWrapper.between("fo.create_time", applyTimeRange[0], applyTimeRange[1]);
        }
        if (ObjUtil.isNotNull(ocBusinessFinancingOrder.getCreditTimeRange()) && ocBusinessFinancingOrder.getCreditTimeRange().length == 2) {
            String[] creditTimeRange = ocBusinessFinancingOrder.getCreditTimeRange();
            queryWrapper.between("fo.credit_time", creditTimeRange[0], creditTimeRange[1]);
        }
        if (StrUtil.isNotBlank(ocBusinessFinancingOrder.getOrderState())) {
            queryWrapper.eq(TABLE_PREFIX + "fo.order_state", ocBusinessFinancingOrder.getOrderState());
        }
        if (ObjUtil.isNotNull(ocBusinessFinancingOrder.getUseCreditTimeRange()) && ocBusinessFinancingOrder.getUseCreditTimeRange().length == 2) {
            String[] useCreditTimeRange = ocBusinessFinancingOrder.getUseCreditTimeRange();
            queryWrapper.between("fo.loan_time", useCreditTimeRange[0], useCreditTimeRange[1]);
        }
//        queryWrapper.eq("fo.site_code",130400);
//        queryWrapper.eq("om.site_code",130400);
        queryWrapper.orderByDesc("create_time");


//        List<SysUserExpand> expandList = iSysUserExpandService.list(new QueryWrapper<SysUserExpand>().eq("user_id", SecurityUtils.getUserId()).eq("user_type",1));
//        List<String> dataPermissions = expandList.stream().map(m -> m.getDataPermission()).collect(Collectors.toList());
        SysUserExpand userExpand = iSysUserExpandService.lambdaQuery().eq(SysUserExpand::getUserId, SecurityUtils.getUserId()).eq(SysUserExpand::getUserType, 1).one();
        if(ObjUtil.isNotNull(userExpand)){
            queryWrapper.apply("instr(fo.org_path,{0}) > 0", userExpand.getDataPermission());
            startPage();
            List<OcBusinessFinancingOrder> list = ocBusinessFinancingOrderService.selectFinancingOrderMatch(queryWrapper);
            return getDataTable(list);
        }
        return getDataTable(Collections.emptyList());

    }

    private void setQueryCondition(OcBusinessFinancingOrderVo ocBusinessFinancingOrder, QueryWrapper<OcBusinessFinancingOrder> queryWrapper) {
        if (StrUtil.isNotBlank(ocBusinessFinancingOrder.getOrderNo())) {
            queryWrapper.eq(TABLE_PREFIX + "fo.order_no", ocBusinessFinancingOrder.getOrderNo());
        }

        if (StrUtil.isNotBlank(ocBusinessFinancingOrder.getEnterpriseName())) {
            queryWrapper.like(TABLE_PREFIX + "om.enterprise_name", ocBusinessFinancingOrder.getEnterpriseName());
        }

        if (StrUtil.isNotBlank(ocBusinessFinancingOrder.getOrganizationName())) {
            queryWrapper.like(TABLE_PREFIX + "fo.organization_name", ocBusinessFinancingOrder.getOrganizationName());
        }

        if (ObjUtil.isNotNull(ocBusinessFinancingOrder.getApplyTimeRange()) && ocBusinessFinancingOrder.getApplyTimeRange().length == 2) {
            String[] applyTimeRange = ocBusinessFinancingOrder.getApplyTimeRange();
            queryWrapper.between("fo.create_time", applyTimeRange[0], applyTimeRange[1]);
        }
        if (ObjUtil.isNotNull(ocBusinessFinancingOrder.getCreditTimeRange()) && ocBusinessFinancingOrder.getCreditTimeRange().length == 2) {
            String[] creditTimeRange = ocBusinessFinancingOrder.getCreditTimeRange();
            queryWrapper.between("fo.credit_time", creditTimeRange[0], creditTimeRange[1]);
        }
        if (StrUtil.isNotBlank(ocBusinessFinancingOrder.getOrderState())) {
            queryWrapper.eq(TABLE_PREFIX + "fo.order_state", ocBusinessFinancingOrder.getOrderState());
        }
        if (ObjUtil.isNotNull(ocBusinessFinancingOrder.getUseCreditTimeRange()) && ocBusinessFinancingOrder.getUseCreditTimeRange().length == 2) {
            String[] useCreditTimeRange = ocBusinessFinancingOrder.getUseCreditTimeRange();
            queryWrapper.between("fo.loan_time", useCreditTimeRange[0], useCreditTimeRange[1]);
        }
        queryWrapper.orderByDesc(TABLE_PREFIX + "fo.create_time");
    }

    /**
     * 导出企业融资订单列表
     */
    @PreAuthorize("@ss.hasPermi('manage:order:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, OcBusinessFinancingOrderVo ocBusinessFinancingOrder, QueryWrapper<OcBusinessFinancingOrder> queryWrapper) {
        if (CollUtil.isEmpty(ocBusinessFinancingOrder.getIds())) {
            setQueryCondition(ocBusinessFinancingOrder, queryWrapper);
        } else {
            queryWrapper.in(TABLE_PREFIX + "id", ocBusinessFinancingOrder.getIds());
        }
        List<OcBusinessFinancingOrder> list = ocBusinessFinancingOrderService.list(queryWrapper);
        ExcelUtil<OcBusinessFinancingOrder> util = new ExcelUtil<OcBusinessFinancingOrder>(OcBusinessFinancingOrder.class);
        util.exportExcel(response, list, "order");
    }

    /**
     * 获取企业融资订单详细信息
     */
    @ApiOperation(value = "获取企业融资订单", notes = "企业融资订单管理")
    @PreAuthorize("@ss.hasPermi('manage:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ocBusinessFinancingOrderService.queryGetById(id));
    }

    /**
     * 新增企业融资订单
     */
    @ApiOperation(value = "新增企业融资订单", notes = "企业融资订单管理")
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@Validated @RequestBody OcBusinessFinancingOrder ocBusinessFinancingOrder) {

        boolean exists = ocBusinessFinancingOrderService.lambdaQuery().eq(OcBusinessFinancingOrder::getMachId, ocBusinessFinancingOrder.getMachId()).exists();
        if(exists){
            throw new CustomException("订单已存在，请勿重复申请");
        }
        return toAjax(ocBusinessFinancingOrderService.addOcBusinessFinancingOrder(ocBusinessFinancingOrder) ? 1 : 0);
    }


    /**
     * 客户经理抢单
     */
    @ApiOperation(value = "新增客户经理抢单", notes = "企业客户经理抢单")
    @RepeatSubmit
    @PostMapping("/grapOrder")
    public AjaxResult grapOrder(@Validated @RequestBody OcBusinessFinancingOrder ocBusinessFinancingOrder) {
        return toAjax(ocBusinessFinancingOrderService.addOcBusinessFinancingOrder(ocBusinessFinancingOrder) ? 1 : 0);
    }

    /**
     * 修改企业融资订单
     */
    @ApiOperation(value = "修改企业融资订单", notes = "企业融资订单管理")
    @PreAuthorize("@ss.hasPermi('manage:order:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody OcBusinessFinancingOrder ocBusinessFinancingOrder) {
        return toAjax(ocBusinessFinancingOrderService.updateOcBusinessFinancingOrder(ocBusinessFinancingOrder) ? 1 : 0);
    }

    /**
     * 删除企业融资订单
     */
    @ApiOperation(value = "删除企业融资订单", notes = "企业融资订单管理")
    @PreAuthorize("@ss.hasPermi('manage:order:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ocBusinessFinancingOrderService.deleteOcBusinessFinancingOrderByIds(ids) ? 1 : 0);
    }

    /**
     * 添加授信记录
     */
    @ApiOperation(value = "添加授信记录", notes = "添加授信记录")
    @PreAuthorize("@ss.hasPermi('manage:order:edit')")
    @RepeatSubmit
    @PostMapping("credit")
    public AjaxResult credit(@RequestBody OcBusinessFinancingOrderVo ocBusinessFinancingOrder) {
        return toAjax(ocBusinessFinancingOrderService.addCredit(ocBusinessFinancingOrder) ? 1 : 0);
    }

    /**
     * 添加用信记录
     */
    @ApiOperation(value = "添加用信记录", notes = "添加用信记录")
    @PreAuthorize("@ss.hasPermi('manage:order:edit')")
    @RepeatSubmit
    @PostMapping("loan")
    public AjaxResult loan(@RequestBody OcBusinessFinancingOrderVo ocBusinessFinancingOrder) {
        return toAjax(ocBusinessFinancingOrderService.addLoan(ocBusinessFinancingOrder) ? 1 : 0);

    }
}
